# Convenience functions that help with data cleaning.

#function that turns negative numbers into NAs. Also can drop outliers
neg_to_na <- function(vec, outlier_top = NULL, outlier_bot = NULL){
  vec[vec < 0] <- NA
  if (!is.null(outlier_top)) vec[vec > outlier_top] <- NA
  if (!is.null(outlier_bot)) vec[vec < outlier_bot] <- NA
  return(vec)
}

#function to reverse values
rev_values <- function(vec){
  vec <- abs(vec - (length(unique(vec) + 1)))
  return(vec)
}

#function to get mode of a numeric, character, factor vector
Mode <- function(x) {
  ux <- unique(x)
  ux[which.max(tabulate(match(x, ux)))]
}

#function to remove NA value labels from all labeled vars
remove_NA_labels <- function(data, na_vec, start = NULL, end = NULL){
  if(is.null(start)){
    start <- 1
    if(is.null(end)){
      end <- ncol(data)  
    } else {
      if(is.character(end)) end <- which(names(data) == end)
    }
  } else{
    if(is.character(start)){
      start <- which(names(data) == start)
    }
    if(is.null(end)){
      end <- ncol(data)
    } else {
      if(is.character(end)) end <- which(names(data) == end)
    }
  }
  
  logicals <- sapply(data, FUN = is.logical)
  
  log_names <- names(data[logicals])
  
  var_names <- names(data[start:end])
  
  var_names <- var_names[!(var_names %in% log_names)]
  
  for(var in var_names){
    for(l in na_vec){
      val_label(data[[var]],l) <- NULL
    }
  }
  return(data)
}

#function to replace by index from a vector by index
replace2 <- function(x, index, values){
  x[index] <- values[index]
  x
}

# negate %in%
'%nin%' <- Negate('%in%')

# function that turns NAs into 0s
NAto0 <- function(x){
  ifelse(is.na(x), 0, x)
}
